package com.gogowan.agroenterprise;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.CheckEquipmentRequest;
import com.gogowan.agroenterprise.model.CheckEquipmentResult;
import com.gogowan.agroenterprise.model.LoginInfo;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.newview.NewMainActivity;
import com.gogowan.agroenterprise.utils.PermissionUtil;
import com.gogowan.agroenterprise.utils.Utils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static java.security.AccessController.getContext;

import org.json.JSONException;
import org.json.JSONObject;

import u.aly.J;

/**
 * @author Maniac
 * @功能 登录模块
 * @date 2012.11.02 11.03 添加记住密码
 */
public class LoginActivity extends BaseActivity {

	private EditText username;
	private EditText password;
	private String name, pwd;
	private Button login;
	private CheckBox checkBox;
	private ProgressDialog progressDialog;
	private boolean isSavePwd = false;
	private boolean isCheckEquipment=false;
	private PermissionUtil permissionUtil;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);
		username = (EditText) findViewById(R.id.login_et_name);
		password = (EditText) findViewById(R.id.login_et_pwd);
		login = (Button) findViewById(R.id.login_btn_login);
		permissionUtil=new PermissionUtil(this);
		checkBox = (CheckBox) findViewById(R.id.login_save_pwd);

		isSavePwd = MyApplication.mSettings.getBoolean("isSavePwd", false);
		if (isSavePwd) {
			String json = MyApplication.mSettings.getString("userPwd", "");
			checkBox.setChecked(true);
			if (json == null || json.equals("")) {

			} else {
				LoginInfo info = (LoginInfo) Utils.fromJSON(
						Utils.decrypt(json), LoginInfo.class);
				username.setText(info.getLoginName());
				password.setText(info.getPassword());
			}
		}

		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				name = username.getText().toString();
				pwd = password.getText().toString();
				// name = "test";
				// pwd = "123456";

				if (Utils.isEmpty(name) || Utils.isEmpty(pwd)) {
					Toast.makeText(LoginActivity.this, "请输入登录信息",
							Toast.LENGTH_LONG).show();
				} else {

					LoginInfo loginInfo = new LoginInfo();
					loginInfo.setLoginName(name);
					loginInfo.setPassword(pwd);

					if (isSavePwd) {
						MyApplication.editor.putString("userPwd",
								Utils.encrypt(Utils.toJSON(loginInfo)));
						MyApplication.editor.commit();
					}

					GetPerisson(loginInfo);

				}

			}
		});

		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
										 boolean isChecked) {

				if (isChecked) {
					MyApplication.editor.putBoolean("isSavePwd", true);
					isSavePwd = true;
				} else {
					MyApplication.editor.putBoolean("isSavePwd", false);
					isSavePwd = false;
				}

				MyApplication.editor.commit();
			}
		});
//		isHaveequipmentPerisson();
	}
	private void GetPerisson(final LoginInfo loginInfo) {
		permissionUtil.setOnPerissionLisner(new PermissionUtil.OnPerissionListener() {
			@Override
			public void OnAllGetResult(List<String> perission_names) {
				MyApplication.editor.putString("token", "");
				MyApplication.editor.commit();
				LoginAsyn loginAsyn = new LoginAsyn();
				loginAsyn.execute(loginInfo);

				progressDialog = ProgressDialog.show(LoginActivity.this,
						getString(R.string.alert_title),
						getString(R.string.alert_message), true, false);
			}

			@Override
			public void OnThrough(List<String> perission_names) {

			}

			@Override
			public void OnError(List<String> perission_names) {
				showToast("权限授予异常，无法登陆！");
			}
		}).getPerission("提示","程序需要设备的摄像头，定位，读写权限，若不给予通过则无法正常登录！",
				PermissionUtil.Permission.CAMERA_PERMISSION.getValue(),
				PermissionUtil.Permission.READ_EXTERNAL_STORAGE.getValue(),
				PermissionUtil.Permission.WRITE_EXTERNAL_STORAGE.getValue(),
				PermissionUtil.Permission.ACCESS_COARSE_LOCATION_PERMISSION.getValue(),
				PermissionUtil.Permission.ACCESS_FINE_LOCATION_PERMISSION.getValue());
	}
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		permissionUtil.onRequestPermissionsResult(requestCode,permissions,grantResults);
	}
	private void isHaveequipmentPerisson() {
		if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
				!= PackageManager.PERMISSION_GRANTED) {
			ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 11);
			return;
		}
		TelephonyManager tm =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		String id=tm.getDeviceId();
		if (!Utils.isEmpty(id)){
			CheckEquipmentRequest request=new CheckEquipmentRequest();
			request.setEquipmentNo(id);
			progressDialog = ProgressDialog.show(LoginActivity.this,
					getString(R.string.alert_title),
					getString(R.string.alert_message), true, false);
			CheckEquipmentAsyn asyn=new CheckEquipmentAsyn();
			asyn.execute(request);
		}else {
			showToast("获取设备码失败，设备无法使用！");
		}
	}

	/**
	 * 异步登录
	 */
	private class LoginAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(LoginActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {

//				Message message = (Message) Utils.fromJSON((String) res,
//						Message.class);
//				String string = Utils.getMessageContent(res);
//				if (string == null || string.equals("")) {
//					Toast.makeText(LoginActivity.this,
//							getString(R.string.analyse_error),
//							Toast.LENGTH_LONG).show();
//				} else {

				String data="";
				try {
					JSONObject jo1=new JSONObject(res+"");
					int code = jo1.getInt("code");
					data = jo1.getJSONObject("data").toString();
					if (code != 200||data==null||"{}".equals(data)) {
						Toast.makeText(LoginActivity.this,
										jo1.getString("msg"), Toast.LENGTH_LONG)
								.show();
						progressDialog.dismiss();
						return;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				LoginResultInfo resultInfo = (LoginResultInfo) Utils.fromJSON(data, LoginResultInfo.class);
				MyApplication.editor.putString(MyApplication.MY_USER_INFO, data);
				MyApplication.editor.putLong("personid", resultInfo.getPersonid());
				MyApplication.editor.putString("password", pwd);
				MyApplication.editor.putString("token", resultInfo.getToken());
				Log.e("DONG", resultInfo.getToken());
				MyApplication.editor.putLong("timeout", resultInfo.getTimeout());
				MyApplication.editor.putInt("usertype", resultInfo.getUserType());
				MyApplication.editor.putString("useraccount", resultInfo.getUseraccount());
				MyApplication.editor.putString("username", resultInfo.getUsername());
				MyApplication.editor.putBoolean("isNew", resultInfo.isIsnew());
				MyApplication.editor.commit();
				if (Build.VERSION.SDK_INT > 24){
					if (isGet()){
						Intent intent = new Intent(LoginActivity.this,
								NewMainActivity.class);
						startActivity(intent);
						LoginActivity.this.finish();
					}
				}else {
					Intent intent = new Intent(LoginActivity.this,
							NewMainActivity.class);
					startActivity(intent);
					LoginActivity.this.finish();
				}
				}
//			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			LoginInfo lInfo = (LoginInfo) params[0];
			String json = Utils.toJSON(lInfo);
//			lInfo.setUsername("admin");

			// String ss = getString(R.string.first_url2);
			String res = Utils.postCommit(
					getString(R.string.first_url) +
						getString(R.string.first_url_page)+
						getString(R.string.login),
					lInfo);
			//https://his.udi.fangzhima.com/jshERP-boot/user/appLogin

			// String res = Utils.postCommit(ss, message);
			return res;
		}

	}

	private class CheckEquipmentAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(LoginActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(LoginActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					CheckEquipmentResult resultInfo = (CheckEquipmentResult) Utils
							.fromJSON(string, CheckEquipmentResult.class);
					if (resultInfo.getResult() >0) {
						if (resultInfo.getAvailable()<0){
							new AlertDialog.Builder(LoginActivity.this)
									.setTitle("提示")
									.setMessage("该设备无法使用，请联系服务商！")
									.setNegativeButton("确定", new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											finish();
										}
									}).show();
						}else {
							isCheckEquipment=true;
						}
					} else {
						Toast.makeText(LoginActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			CheckEquipmentRequest checkEquipmentRequest = (CheckEquipmentRequest) params[0];
			String json = Utils.toJSON(checkEquipmentRequest);
			Message message = new Message(44000, true, json);
			// String ss = getString(R.string.first_url2);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			// String res = Utils.postCommit(ss, message);
			return res;
		}

	}

	private boolean isGet() {
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
				!= PackageManager.PERMISSION_GRANTED){
			ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 10);
			return false;
		}
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
				!= PackageManager.PERMISSION_GRANTED){
			ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 10);
			return false;
		}
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS)
				!= PackageManager.PERMISSION_GRANTED){
			ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CONTACTS}, 10);
			return false;
		}
		return  true;
	}

}
